package ilender.facebook;

import java.util.EnumMap;
import java.util.Map;
import java.net.URLEncoder;

import lombok.*;
import com.google.gson.*;

import ilender.models.*;
import ilender.util.*;

/**
 * Handler for a Facebook post.
 */
public class FBPost{
	public final FBObject fbObject;
	public final FBPostType type;
	private Map<FBPostField,String> fields;

	@Getter private String message;

	/**
	 * Constructor.
	 *
	 * @param fbObject The object to post on it's feed.
	 * @param type The type of the post.
	 */
	FBPost(FBObject fbObject,FBPostType type){
		this.fbObject=fbObject;
		this.type=type;
		fields=new EnumMap<FBPostField,String>(FBPostField.class);
	}

	/**
	 * Sets a post field.
	 *
	 * @param field The field to set.
	 * @param value The value to set to that field.
	 * @return Self.
	 */
	public FBPost setField(FBPostField field,String value){
		fields.put(field,value);
		return this;
	}

	/**
	 * Sets the message field.
	 *
	 * @param message The message to set.
	 * @return Self.
	 */
	public FBPost setMessage(String message){
		return setField(FBPostField.MESSAGE,message);
	}

	/**
	 * Sets the link field.
	 *
	 * @param link The link to set.
	 * @return Self.
	 */
	public FBPost setLink(String link){
		return setField(FBPostField.LINK,link);
	}

	public FBPost setLink(BaseModel model){
		String appUrl=PropertiesTools.fetchFacebookProperties().getProperty("app-url");
		return setLink(String.format("%s?fb_ref=%s",appUrl,
					URLEncoder.encode(String.format("%s#%s",model.getClass().getSimpleName(),model.getId()))));
	}

	/**Perform the actual post.*/
	public void post(){
		String[] fieldArgs=new String[2*fields.size()];
		int i=0;
		for(val entry:fields.entrySet()){
			fieldArgs[i++]=entry.getKey().name().toLowerCase();
			fieldArgs[i++]=entry.getValue();
		}
		val result=fbObject.graphAPI.makePostRequest(String.format("%s/%s",fbObject.id,type.name().toLowerCase()),fieldArgs);
		System.out.println(result);
		if(result.getAsJsonObject().has("id")){
			val resultId=result.getAsJsonObject().get("id").getAsString().split("_")[1];
			System.out.println(resultId);
		}
	}
}
